package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.asn1.axdr.AxdrOptional;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

/**
 * FjCAPdu类
 * 实现客户端APDU的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class FjCAPdu implements AxdrType {

    private byte[] dataCode = null;
    private AxdrOptional<TimeTag> timeTag = new AxdrOptional<TimeTag>(new TimeTag(), false);

    public FjCAPdu() {
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setTimeTag(TimeTag timeTag) {
        this.timeTag.setValue(timeTag);
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;
        this.timeTag = new AxdrOptional<TimeTag>(new TimeTag(), false);
        try {
            codeLength += this.timeTag.decode(input);
        } catch (java.io.IOException e) {
            throw new RuntimeException("IO exception during decode", e);
        }
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(this.dataCode[i]);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("IO exception during encode", e);
                }
            }
        } else {
            if (this.timeTag != null) {
                codeLength = 0;
                try {
                    codeLength += this.timeTag.encode(output);
                } catch (java.io.IOException e) {
                    throw new RuntimeException("IO exception during encode", e);
                }
            } else {
                throw new RuntimeException("timeTag is null");
            }
        }
        System.out.println(codeLength);
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (this.timeTag != null) {
            return "sequence: {" + "timeTag: " + this.timeTag + "}";
        } else {
            return "timeTag is null";
        }
    }
}